import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as API from "../api/http";

let initialState = {
    shoplist: [],
    typelist: [],
    carlist: []
}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: {
        //获取商品列表数据
        t_shoplist(state, action): any {
            state.shoplist = action.payload
        },
        //获取分类列表数据
        t_typelist(state, action): any {
            state.typelist = action.payload
        },
        //获取购物车数据
        t_carlist(state, action): any {
            state.carlist = action.payload
        },
        //添加数据
        t_addshoplist(state, action) {
            state.carlist.push(action.payload)
        },
        //编辑数据
        t_updateshoplist(state, action) {
            let i = state.carlist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.carlist[i] = action.payload
        }
    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;


/* 商品列表数据 */
export let async_shoplist = createAsyncThunk('async_shoplist', async (_, store) => {
    //调取接口
    let res = await API.http_getshoplist()
    //同步修改异步
    store.dispatch(actionfn.t_shoplist(res))
})

/* 分类列表数据 */
export let async_typelist = createAsyncThunk('async_typelist', async (_, store) => {
    //调取接口
    let res = await API.http_gettypelist()
    //同步修改异步
    store.dispatch(actionfn.t_typelist(res))
})

//获取购物车数据

export let async_carlist = createAsyncThunk('async_carlist', async (_, store) => {
    //调取接口
    let res = await API.http_getcarlist()
    //同步修改异步
    store.dispatch(actionfn.t_carlist(res))
})

/* 添加商品列表数据 */
export let async_addshoplist = createAsyncThunk('async_addshoplist', async (obj, store) => {
    //调取接口
    let res = await API.http_addshoplist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_addshoplist(res))
})

/* 编辑商品列表数据 */
export let async_updateshoplist = createAsyncThunk('async_updateshoplist', async (obj, store) => {
    //调取接口
    let res = await API.http_updateshoplist(obj)
    //同步修改异步
    store.dispatch(actionfn.t_updateshoplist(res))
})





